home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6258 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  88 lines

  1. Path: faatcrl.faa.gov!saratoga!lbona
  2. From: lbona@saratoga (lbona)
  3. Newsgroups: comp.lang.c
  4. Subject: returning ptr to struct with ptrs in it?
  5. Date: 23 Feb 1996 11:24:18 GMT
  6. Organization: FAA Technical Center, Pomona, NJ
  7. Message-ID: <4gk852INNbp4@faatcrl.faa.gov>
  8. NNTP-Posting-Host: 155.178.247.116
  9. X-Newsreader: Tin 1.1 PL4
  10.  
  11.  
  12. The following is beyond the scope of my knowledge. Perhaps someone can explain
  13. it to me:
  14.  
  15. When I declare a function that returns a pointer to a struct that contains 
  16. pointers, the pointer(s) at the end of the struct get set to garbage after 
  17. being returned. Pointers not at the end are not affected.
  18.  
  19. --------------------------------------------------------------
  20.  
  21. typedef struct aaa {
  22.   int i;
  23.   char name[22];
  24.   int id;
  25. } AAA;
  26.  
  27. typedef struct bar {
  28.   long a;
  29.   long b;
  30.   int c;
  31.   AAA *d;
  32.   char e;
  33.   char f[100];
  34.   AAA *g;
  35.   AAA *h;
  36. } BAR;
  37.  
  38. BAR *parse_bar(char toke[]);
  39.  
  40. main()
  41. {
  42. BAR BB;
  43. char toke[128];
  44.  
  45.   memset(&BB,0,sizeof(BAR));
  46.    /* at this point BB.d == BB.g == BB.h == NULL */
  47.  
  48.     /* toke is an ascii string read in from a file */
  49.   BB = *parse_bar(toke);
  50.  
  51.   /* at this point BB.g and BB.h are garbage, but all the other fields */
  52.   /* in BB are correct including BB.d*/
  53.  
  54. }
  55.  
  56.  
  57. BAR *parse_bar(char toke[]);
  58. {
  59. BAR bb;
  60.  
  61.   memset(&bb,0,sizeof(BAR));
  62.    /* at this point BB.d == BB.g == BB.h == NULL */
  63.  
  64.   /* read data from file and parse - never touch bb.d, bb.g, or bb.h */
  65.  
  66.    /* at this point BB.d == BB.g == BB.h == NULL */
  67.   return(&bb);
  68. }
  69.  
  70.  
  71. ----------------------------------------------------------
  72.  
  73. I know there are several work arounds, and that it's better to pass the address
  74. of BB to parse_bar(), which is what I'll be doing. But I'm curious why this is
  75. happening. I've tried it under K&R on Unix and ANSI on DOS and the results
  76. were identical.
  77.  
  78.  
  79. Any help would be appreciated,
  80.  
  81. thanks
  82.  
  83. --
  84.  
  85. Lou Bona
  86. lbona@tgf.tc.faa.gov
  87.  
  88.